package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @Author: bowen
 * @Date: 2019/7/19 15:52
 * @Description:订单
 */

@RestController
@RequestMapping("/order")
public class OrderController {

	@Autowired
	JedisPool jedisPool;

	@Reference
	OrderService orderService;

    /**
     *  @描述：提交预约订单
     */
    @RequestMapping("/submit")
	public Result submit(@RequestBody Map orderInfo) {
    	Result result=null;
    	// 校验验证码是不是正确，如果错误，返回错误信息
	    // 前端传过来的验证码
	    String validateCode = String.valueOf(orderInfo.get("validateCode"));
	    // 获取手机号
	    String telephone = String.valueOf(orderInfo.get("telephone"));
	    // 获取预约时间
	    String orderDate = String.valueOf(orderInfo.get("orderDate"));
	    // redis验证码
	    String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
	    if(ObjectUtils.isEmpty(codeInRedis) || !codeInRedis.equals(validateCode)){
	    	return  new Result(false, MessageConstant.VALIDATECODE_ERROR);
	    }
	    //   验证码校验通过，通过服务新增预约订单
        try {


	        orderInfo.put("orderType", Order.ORDERTYPE_WEIXIN);
	        result = orderService.add(orderInfo);

        } catch (Exception e){
	        e.printStackTrace();
	        return new Result(false,MessageConstant.ORDER_FAIL);
        }
	    // 预约成功，发送成功短信
	    if(result.isFlag()){
	    try {
		    SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, telephone, orderDate);
	    } catch (ClientException e) {
		    e.printStackTrace();
	    }}
	    return result;
	}

	//public static void main(String[] args) {
	//	CheckItem checkItem = new CheckItem();
	//	checkItem = null;
	//	String.valueOf(checkItem);
	//}
	/**
	 *  @描述：根据id查询订单信息
	 */
	@RequestMapping("/findById")
	public Result findById(Integer id) {
		try {
			Map map = orderService.findById(id);
			return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
		} catch(Exception e){
			e.printStackTrace();
			return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
		}
	}
}
